/*
 * @Author: zhangchaosen
 * @Date: 2024-05-20 09:29:53
 * @LastEditors: zhangchaosen
 * @LastEditTime: 2024-06-18 13:46:18
 * @Description:
 */
import store from '@/store'
import { defineStore } from 'pinia'

interface State {
  // 存储的请求控制器
  controllers: AbortController[]
}

export const useRequestStore = defineStore({
  id: 'geek-request',
  state: (): State => ({
    controllers: []
  }),
  actions: {
    /** 添加请求 */
    add(controller: AbortController) {
      this.controllers.push(controller)
    },
    /** 清除请求 */
    clear() {
      if (this.controllers.length === 0) return
      this.controllers.forEach((controller: AbortController) => {
        // 取消请求
        controller.abort()
      })
      this.controllers = []
    }
  }
})

/** 在 setup 外使用 */
export function useRequestStoreHook() {
  return useRequestStore(store)
}
